<?php
/**
 * Created by PhpStorm.
 * User:lyq
 * Date: 2018/8/25
 * Time: 17:08
 */

namespace app\admin\controller;

use app\admin\model\Wallet;
use app\common\model\Commission;
use app\common\model\Member;
use app\common\model\Message;
use think\Exception;
use think\Db;
use think\exception\ErrorException;
use think\Session;
use app\common\model\User as commonuser;

class User extends Common
{
    public function index()
    {
        //标题
        $this->templateTitle("会员列表");
        $where['us.id'] = ['gt', 0];

        //搜索条件-推荐人手机号
        $parent_mobile = request()->param("parent_mobile");
        /*推荐人信息*/
        $parent = db('user')
            ->where('mobile', $parent_mobile)
            ->find();
        if (!empty($parent_mobile)) {
            if (!empty($parent)) {
                $where["us.parent_id"] = $parent['id'];
            } else {
                $where["us.id"] = '-1';/*让结果为空*/
            }
        }
        $this->assign("parent_mobile", $parent_mobile);

        //搜索条件-手机
        $mobile = request()->param("mobile");
        $this->assign("mobile", $mobile);
        if ($mobile) {
            $where["us.mobile"] = $mobile;
        }
        //搜索条件-姓名
        $nick_name = request()->param("nick_name");
        $this->assign("nick_name", $nick_name);
        if ($nick_name) {
            $where["us.nick_name"] = ['like', "%$nick_name%"];
        }

        //会员身份
        $user_type = input("user_type");
        if(!empty($user_type)){
            if($user_type == 1){
                $where["brand_id"] = "";
            }else{
                $where["brand_id"] = ["neq", ""];
            }
        }
        $this->assign("user_type", $user_type);


        //搜索条件-注册时间
        if (request()->has("time_range")) {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['us.create_time'] = [
                ["EGT", strtotime($timeRange[0] . " 00:00:00")],
                ["ELT", strtotime($timeRange[1] . " 23:59:59")]
            ];

        } else {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '2018-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }
        //获取所有用户
        $list = Db::name("user")
            ->alias('us')
            ->where($where)
            ->order("us.id DESC")
            ->paginate(10);
        //获取品牌信息
        $brand = db("brand")->column("title", "id");
        $this->assign("brand", $brand);

        $this->assign("list", $list);
        return $this->fetch();
    }

    /*会员的团队列表*/
    public function invite()
    {
        $this->layoutModal();
        $type = input('type');
        $uid = input('id');
        $children = Commission::getTotal($uid);
        if ($type == 1) {
            $list = \db("user")->whereIn("id", $children["children1"])->select();
        } else {
            $list = \db("user")->whereIn("id", $children["children2"])->select();
        }
        $this->assign('all_num', count($list));
        $this->assign('list', $list);
        return $this->fetch();
    }

    /*拉黑或者取消拉黑会员*/
    public function blacklist()
    {
        if (request()->isAjax()) {
            $id = request()->param("id");
            //状态
            $status = request()->param("status");

            if (!in_array($status, [0, 1])) {
                return $this->ajaxError('操作参数有误');
            }
            try {
                $s = Db::name("user")
                    ->where("id", $id)
                    ->update(array(
                        "in_blacklist" => $status,
                        "update_time" => time(),
                    ));
                if ($s) {
                    if ($status == 1) {
                        /*操作日志*/
                        Message::admin_log($id, "后台拉黑会员！");
                        return $this->ajaxSuccess('拉黑操作成功！');
                    } else {
                        /*操作日志*/
                        Message::admin_log($id, "后台取消会员的拉黑！");
                        return $this->ajaxSuccess('取消拉黑操作成功！');
                    }

                } else {
                    return $this->ajaxError('服务器繁忙，请稍后再试');
                }
            } catch (Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }

        }
    }

    /*修改会员信息*/
    public function edit()
    {
        $id = request()->param('id');
        if (request()->isGet()) {
            $this->layoutModal();
            $info = Db::name('user')->where('id', $id)->find();
            $this->assign('info', $info);
            //获取可使用品牌
            $brand_list = \db("brand")->where("is_visible", 1)->where("is_valid", 1)->column("title", "id");
            $this->assign("brand_list", $brand_list);
            $this->assign("brand_list_checked", explode(",", $info["brand_id"]));
            //头像
            $this->assign("single_image", array("avatar" => $info["avatar"]));
            return $this->fetch();
        }

        if (request()->isAjax()) {
            $where['id'] = $id;
            $mobile = trim(request()->param('mobile'));
            $nick_name = trim(request()->param('nick_name'));
            $password = trim(request()->param('password'));
            $avatar = trim(request()->param('avatar'));
            $in_blacklist = trim(request()->param('in_blacklist'));
            $brand_ids = input("brand_id/a")?:[];
            $brand_id = implode(",", $brand_ids);
            try {
                $data = [
                    'nick_name' => $nick_name,
                    'avatar' => $avatar,
                    'in_blacklist' => $in_blacklist,
                    'update_time' => time(),
                    'brand_id'=>$brand_id
                ];

                if (!empty($password)) {
                    $data['password'] = md5(md5($password));
                }

                $save = Db::name('user')
                    ->where($where)
                    ->update($data);
                /*操作记录*/
                Message::admin_log($id, "后台修改会员资料！");
                if ($save) {
                    $this->ajaxSuccess('会员编辑成功');
                } else {
                    $this->ajaxError('数据库繁忙，编辑失败');
                }

            } catch (Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    /*添加会员*/
    public function add()
    {
        if (request()->isGet()) {
            $this->layoutModal();
            //获取可使用品牌
            $brand_list = \db("brand")->where("is_visible", 1)->where("is_valid", 1)->column("title", "id");
            $this->assign("brand_list", $brand_list);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            $parent_mobile = input("invite_code")?:0;
            $mobile = trim(request()->param('mobile'));
            $nick_name = trim(request()->param('nick_name'));
            $password = trim(request()->param('password'));
            $confirm_password = trim(request()->param('confirm_password'));
            $avatar = trim(request()->param('avatar'));
            $brand_ids = input("brand_id/a")?:[];
            $brand_id = implode(",", $brand_ids);
            try {
                $id = \app\common\model\User::register($nick_name, $mobile, $password, $confirm_password, $parent_mobile, $avatar, $brand_id);
                /*操作记录*/
                Message::admin_log($id, "后台添加会员！");
                if ($id) {
                    $this->ajaxSuccess('会员添加成功');
                } else {
                    $this->ajaxError('数据库繁忙，添加失败');
                }

            } catch (\Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

}

